package com.ashes.security.frame;

import com.ashes.belife.common.config.RedisCache;
import com.ashes.belife.common.exception.AshesException;
import com.ashes.belife.common.utils.JwtUtil;
import com.ashes.belife.common.utils.ResultCodeEnum;
import io.jsonwebtoken.Claims;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * @author chengxuhui
 */

public class RequestTokenUtil {

    public static BigDecimal getUserId(HttpServletRequest request, RedisCache redisCache){
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new AshesException(ResultCodeEnum.ILLEGAL_REQUEST);
        }
        LoginUser loginUser = analysisToken(token, redisCache);
        return loginUser.getUser().getUserId();
    }

    public static LoginUser analysisToken(String token, RedisCache redisCache){
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            throw new AshesException("用户登录失效,请重新登录");
        }
        //从redis中获取用户信息
        String redisKey = "login:" + userid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        return loginUser;
    }
    public static Boolean deleteToken(String token, RedisCache redisCache){
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中删除用户信息
        String redisKey = "login:" + userid;
        boolean flag = redisCache.deleteObject(redisKey);
        return flag;
    }
}